package id.amikom.jogjabankfinder.activity;

import java.util.ArrayList;

import org.json.JSONObject;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import id.amikom.jogjabankfinder.GPSHelper;
import id.amikom.jogjabankfinder.JSONHelper;
import id.amikom.jogjabankfinder.R;
import id.amikom.jogjabankfinder.Utils;
import id.amikom.jogjabankfinder.entity.Bank;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class PetaLokasi extends FragmentActivity implements OnItemSelectedListener, OnInfoWindowClickListener,
		LocationListener
{
	private GoogleMap			map;
	private GPSHelper			gps;
	private LocationManager		locManager;
	private Location			location;
	private JSONHelper			json;
	private LatLng				myLocation;
	private Context				context;

	private ArrayList<Bank>		listBank;
	private Marker				markerMyLocation;
	private final int			ZOOM	= 14;

	private ProgressDialog		pDialog;

	private Spinner				spLokasiBank;
	private ArrayList<String>	listBankSpinner;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bank_location);

		spLokasiBank = (Spinner) findViewById(R.id.spinnerBank);
		spLokasiBank.setOnItemSelectedListener(this);
		locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		context = this;

		json = new JSONHelper();

		new AsycnTaskBank().execute();

		setupGPS();

		setupMapIfNeeded();
	}

	private void setupGPS()
	{
		gps = new GPSHelper(context, locManager, this);
		location = gps.getLocation();

		if (location != null)
		{
			myLocation = new LatLng(location.getLatitude(),
					location.getLongitude());
			onLocationChanged(location);
		}
	}

	private void setupMapIfNeeded()
	{

		if (map == null)
		{
			Utils.TRACE("API " + Build.VERSION.SDK_INT);
			FragmentManager fragmentManager = getSupportFragmentManager();
			SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
			map = supportMapFragment.getMap();

			if (map != null)
			{
				setupMap();
			}
		}

	}

	private void setupMap()
	{
		map.setOnInfoWindowClickListener(this);

		if (myLocation != null)
		{
			markerMyLocation = map.addMarker(new MarkerOptions()
					.position(myLocation)
					.title("Posisi anda")
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

			map.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 14));

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			startActivity(new Intent(PetaLokasi.this, MenuUtama.class));
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void tampilSpinner()
	{
		// TODO Auto-generated method stub
		ArrayAdapter<String> bankAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				listBankSpinner);
		bankAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spLokasiBank.setAdapter(bankAdapter);

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int loc, long arg3)
	{
		// TODO Auto-generated method stub

		if (loc != 0)
		{
			tampilBank(loc);
		}

	}

	private void tampilBank(int i)
	{
		i -= 1;
		double lat = listBank.get(i).getLat();
		double lng = listBank.get(i).getLng();

		map.animateCamera((CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng),
				ZOOM)));

	}

	@Override
	public void onInfoWindowClick(Marker marker)
	{
		// TODO Auto-generated method stub

		Bundle bundle = new Bundle();

		bundle.putString("to", marker.getTitle());
		bundle.putDouble("start_lat", myLocation.latitude);
		bundle.putDouble("start_lng", myLocation.longitude);
		bundle.putDouble("end_lat", marker.getPosition().latitude);
		bundle.putDouble("end_lng", marker.getPosition().longitude);

		Intent i = new Intent(PetaLokasi.this,
				Navigasi.class);
		i.putExtras(bundle);
		startActivity(i);
		finish();
	}

	@Override
	public void onLocationChanged(Location location)
	{
		// TODO Auto-generated method stub
		Toast.makeText(this, "Lokasi berubah", Toast.LENGTH_SHORT).show();

		if (markerMyLocation != null)
		{
			markerMyLocation.remove();
			markerMyLocation = map.addMarker(new MarkerOptions()
					.position(new LatLng(location.getLatitude(),
							location.getLongitude()))
					.title("Posisi anda")
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
			map.animateCamera(CameraUpdateFactory.newLatLngZoom(new
					LatLng(location.getLatitude(), location.getLongitude()),
					14));

		}
	}

	@Override
	public void onProviderDisabled(String provider)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{
		// TODO Auto-generated method stub

	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();

		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
		if (resultCode == ConnectionResult.SUCCESS)
		{
			Utils.TRACE("Google service ada");
		} else
		{
			GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
		}

		// setupMapIfNeeded();
	}

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onStart()
	{
		// TODO Auto-generated method stub
		super.onStart();
		// gps.checkGPS();
	}

	@Override
	protected void onStop()
	{
		// TODO Auto-generated method stub
		super.onStop();
		// locManager.removeUpdates(this);
		gps.stopGPS();
	}

	private class AsycnTaskBank extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params)
		{
			// TODO Auto-generated method stub
			String URL = "http://jogjabankfinder.tk/lokasibank.php";

			JSONObject jObj = json.getJSONFromUrl(URL);
			listBank = json.getAllBankLocation(jObj);

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub

			pDialog.dismiss();
			runOnUiThread(new Runnable()
			{

				@Override
				public void run()
				{
					// TODO Auto-generated method stub
					listBankSpinner = new ArrayList<String>();
					listBankSpinner.add("Daftar Bank");

					for (int i = 0; i < listBank.size(); i++)
					{
						listBankSpinner.add(listBank.get(i).getName());

						map.addMarker(new MarkerOptions()
								.position(new LatLng(listBank.get(i).getLat(), listBank.get(i)
										.getLng()))
								.title(listBank.get(i).getName())
								.snippet(listBank.get(i).getDesc()));
					}

				}
			});

			tampilSpinner();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(PetaLokasi.this);
			pDialog.setMessage("Loading....");
			pDialog.setCancelable(true);
			pDialog.show();
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0)
	{
		// TODO Auto-generated method stub

	}
}
